package com.bsoft.service.impl;

import cn.hutool.json.JSONUtil;
import com.bsoft.mapper.business.FoodborneIllnessMapper;
import com.bsoft.service.FoodborneIllnessService;
import com.bsoft.utils.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.bsoft.utils.DateUtil.parseDateTime;

@Service
@EnableTransactionManagement
public class FoodborneIllnessServiceImpl extends ConmonUtil implements FoodborneIllnessService  {
    private static Logger logger = LoggerFactory.getLogger(FoodborneIllnessServiceImpl.class);
    @Autowired
    private FoodborneIllnessMapper foodborneIllnessMapper;

    @Value("http://10.100.0.28:8090/ReportService.svc?wsdl")
    private String url;

    @Value("https://hihis.yxszyyy.cn/BS-DSCS2.1/*.jsonRequest")
    private String url_bk;

    /**食源性上报数据查询*/
    @Override
    public String queryEscalationStatusList(Map<String, Object> req) throws Exception{
        req.put("startTiem",parseDateTime(String.valueOf(req.get("startTiem"))));
        req.put("endTiem",parseDateTime(String.valueOf(req.get("endTiem"))));
        //业务处理
        List<Map<String ,Object>> resList = foodborneIllnessMapper.queryEscalationStatusList(req);
        return getSuccess(JSONArray.fromObject(resList));
    }

    /**食源性上报病例数据更新*/
    @Override
    public String updateEscalationStatus(Map<String, Object> req) {
        req.put("ID_REPORT",String.valueOf(req.get("病例ID")));
        req.put("SBZT",String.valueOf(req.get("SBZT")));
        req.put("GUID",String.valueOf(req.get("病例")));
        //业务处理
         foodborneIllnessMapper.updateEscalationStatus(req);
        return getSuccess(JSONArray.fromObject(""));
    }

    /**
     * 食源性报卡新建病例
     */
    @Override
    public String loadFoodborneIllness(Map<String, Object> req) {
        //上传数据业务逻辑处理
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("接口");
        root.addElement("令牌").addText(stringOf(req.get("令牌")));
        root.addElement("数据类型").addText("7");
        root.addElement("操作类型").addText("1");
        root.addElement("操作单位").addText(stringOf(req.get("操作单位")));
        root.addElement("操作用户").addText(stringOf(req.get("操作用户")));
        Element bl = root.addElement("病例");
        bl.addAttribute("Guid",stringOf(req.get("病例")));
        bl.addElement("病例编号").addText(stringOf(req.get("病例编号")));
        Element tbxx = bl.addElement("填报信息");
        tbxx.addElement("填报人").addText(stringOf(req.get("填报人")));
        tbxx.addElement("接诊医生").addText(stringOf(req.get("接诊医生")));
        tbxx.addElement("填表时间").addText(stringOf(req.get("填表日期")));
        tbxx.addElement("医疗机构").addText(stringOf(req.get("医疗机构")));

        bl.addElement("发病时间").addText(stringOf(req.get("发病时间")));
        bl.addElement("就诊时间").addText(stringOf(req.get("就诊时间")));
        bl.addElement("门诊号").addText(stringOf(req.get("门诊号")));
        bl.addElement("是否复诊").addText(stringOf(req.get("是否复诊")));
        bl.addElement("是否住院").addText(stringOf(req.get("是否住院")));
        bl.addElement("住院号").addText(stringOf(req.get("住院号")));
        bl.addElement("死亡时间").addText(stringOf(req.get("死亡时间")));
        bl.addElement("患者姓名").addText(stringOf(req.get("患者姓名")));
        bl.addElement("监护人姓名").addText(stringOf(req.get("监护人姓名")));
        bl.addElement("患者性别").addText(stringOf(req.get("患者性别")));
        bl.addElement("患者职业").addText(stringOf(req.get("患者职业")));
        bl.addElement("身份证号").addText(stringOf(req.get("身份证号")));
        bl.addElement("出生日期").addText(stringOf(req.get("出生日期")));
        bl.addElement("联系电话").addText(stringOf(req.get("联系电话")));
        bl.addElement("工作单位").addText(stringOf(req.get("工作单位")));
        bl.addElement("患者属于").addText(stringOf(req.get("患者属于")));

        Element xzz = bl.addElement("现在住址");
        xzz.addElement("省市县").addText(stringOf(req.get("省市县")));
        xzz.addElement("详细地址").addText(stringOf(req.get("详细地址")));

        Element zttz = bl.addElement("主要症状与体征");
        Element qszttzfr = zttz.addElement("发热");
        qszttzfr.addElement("度数").addText(stringOf(req.get("症状发热_度数")));
        zttz.addElement("面色潮红").addText(stringOf(req.get("症状_面色潮红")));
        zttz.addElement("肥皂咸味").addText(stringOf(req.get("肥皂咸味")));
        Element qszttzxhxt = zttz.addElement("消化系统");
        Element qszttzxhxtfxzz = qszttzxhxt.addElement("腹泻性状");
        qszttzxhxtfxzz.addElement("性状").addText(stringOf(req.get("症状腹泻_性状")));
        qszttzxhxtfxzz.addElement("次数").addText(stringOf(req.get("症状腹泻_次数")));
        Element qszttzxhxtqt = zttz.addElement("其他");
        qszttzxhxtqt.addElement("名称").addText(stringOf(req.get("其他名称")));

        Element zdxx = bl.addElement("诊断结论");
        zdxx.addElement("菜豆中毒").addText(stringOf(req.get("菜豆中毒")));
        zdxx.addElement("急性胃肠炎").addText(stringOf(req.get("诊断结论_急性胃肠炎")));
        Element qtsyxjb = zdxx.addElement("其他食源性疾病");
        qtsyxjb.addElement("名称").addText(stringOf(req.get("名称")));

        Element kss = bl.addElement("抗生素");
        kss.addElement("是否使用抗生素").addText(stringOf(req.get("是否使用抗生素")));
        kss.addElement("抗生素名称").addText(stringOf(req.get("抗生素名称")));

        Element jwbs = bl.addElement("既往病史");
        jwbs.addElement("一般消化道炎症").addText(stringOf(req.get("一般消化道炎症")));
        Element jwbsqt = bl.addElement("其他");
        jwbsqt.addElement("名称").addText(stringOf(req.get("名称")));

        Element bbxx = bl.addElement("暴露信息");
        Element bbxxtm = bbxx.addElement("暴露信息条目");
        bbxxtm.addElement("食品名称").addText(stringOf(req.get("暴露信息_食品名称")));
        bbxxtm.addElement("食品分类").addText(stringOf(req.get("暴露信息_食品分类")));
        bbxxtm.addElement("加工或包装方式").addText(stringOf(req.get("暴露信息_加工或包装方式")));
        bbxxtm.addElement("食品品牌").addText(stringOf(req.get("暴露信息_食品品牌")));
        bbxxtm.addElement("生产厂家").addText(stringOf(req.get("暴露信息_生产厂家")));
        bbxxtm.addElement("进食场所").addText(stringOf(req.get("暴露信息_进食场所")));
        bbxxtm.addElement("购买场所").addText(stringOf(req.get("暴露信息_购买场所")));
        Element bbxxjsdd = bbxxtm.addElement("进食地点");
        bbxxjsdd.addElement("境内境外").addText(stringOf(req.get("进食地点_境内境外")));
        bbxxjsdd.addElement("省市县").addText(stringOf(req.get("进食地点_省市县")));
        bbxxjsdd.addElement("详细地址").addText(stringOf(req.get("进食地点_详细地址")));
        Element bbxxgmdd = bbxxtm.addElement("购买地点");
        bbxxgmdd.addElement("境内境外").addText(stringOf(req.get("购买地点_境内境外")));
        bbxxgmdd.addElement("省市县").addText(stringOf(req.get("购买地点_省市县")));
        bbxxgmdd.addElement("详细地址").addText(stringOf(req.get("购买地点_详细地址")));

        bbxxtm.addElement("进食人数").addText(stringOf(req.get("进食人数")));
        bbxxtm.addElement("进食时间").addText(stringOf(req.get("进食时间")));
        bbxxtm.addElement("他人是否发病").addText(stringOf(req.get("他人是否发病")));

        Element fj = bl.addElement("附件");
        fj.addElement("附件名称").addText(stringOf(req.get("附件名称")));
        fj.addElement("附件流").addText(stringOf(req.get("附件流")));
        //组装上传德数据
        String xml = document.asXML();
        logger.info("新建病例调用接口入参:{}",xml);
        String result;
        //调用上传地址
        try {
            String base64Encoder = Base64Utils.getBase64Encoder(xml);
            String invoke = ClientUtil.invoke(url, "WEBRequest", base64Encoder);
            logger.info("调用接口出参:{}",invoke);
            result = Base64Utils.getBase64Decoder(invoke);
            logger.info("调用接口出参解密:{}",result);
            Document documentResult = DocumentHelper.parseText(result);
            Element rootResult = documentResult.getRootElement();
            //Element element = rootResult.element("接口");
            Element elementCzzt = rootResult.element("操作状态");
            if (elementCzzt != null) {
                String code = elementCzzt.getText(); // 或 element.getTextTrim()
                if ("1".equals(code)){
                    Map param = new HashMap<>();
                    param.put("ID_REPORT",req.get("病例ID"));
                    param.put("SBZT",1);
                    param.put("GUID",req.get("病例"));
                    updateEscalationStatus(param);
                    return  getSuccess(JSONArray.fromObject(result));
                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

//        HttpClientUtil.doPost();
        return result;
    }

    /**
     * 食源性报卡上报病例
     */
    @Override
    public String updateFoodborneIllness(Map<String, Object> req) {
        //上传数据业务逻辑处理
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("接口");
        root.addElement("令牌").addText(stringOf(req.get("令牌")));
        root.addElement("数据类型").addText("3");
        root.addElement("操作类型").addText("4");
        root.addElement("操作单位").addText(stringOf(req.get("操作单位")));
        root.addElement("操作用户").addText(stringOf(req.get("操作用户")));
        root.addElement("病例").addText(stringOf(req.get("病例")));

        //组装上传德数据
        String xml = document.asXML();
        logger.info("上传病例调用接口入参:{}",xml);
        String result;
        //调用上传地址
        try {
            String base64Encoder = Base64Utils.getBase64Encoder(xml);
            String invoke = ClientUtil.invoke(url, "WEBRequest", base64Encoder);
            logger.info("调用接口出参:{}",invoke);
            result = Base64Utils.getBase64Decoder(invoke);
            logger.info("调用接口出参解密:{}",result);
            Document documentResult = DocumentHelper.parseText(result);
            Element rootResult = documentResult.getRootElement();
//            Element element = rootResult.element("接口");
            Element elementCzzt = rootResult.element("操作状态");
            if (elementCzzt != null) {
                String code = elementCzzt.getText(); // 或 element.getTextTrim()
                if ("1".equals(code)){
                    Map param = new HashMap<>();
                    param.put("ID_REPORT",req.get("病例ID"));
                    param.put("SBZT",2);
                    param.put("GUID",req.get("病例"));
                    updateEscalationStatus(param);
                    return  getSuccess(JSONArray.fromObject(result));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

//        HttpClientUtil.doPost();
        return result;
    }

    /**
     * 食源性报卡删除病例
     */
    @Override
    public String deleteFoodborneIllness(Map<String, Object> req) {
        //上传数据业务逻辑处理
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("接口");
        root.addElement("令牌").addText(stringOf(req.get("令牌")));
        root.addElement("数据类型").addText("3");
        root.addElement("操作类型").addText("3");
        root.addElement("操作单位").addText(stringOf(req.get("操作单位")));
        root.addElement("操作用户").addText(stringOf(req.get("操作用户")));
        root.addElement("病例").addText(stringOf(req.get("病例")));

        //组装上传德数据
        String xml = document.asXML();
        logger.info("删除病例调用接口入参:{}",xml);
        String result;
        //调用上传地址
        try {
            String base64Encoder = Base64Utils.getBase64Encoder(xml);
            String invoke = ClientUtil.invoke(url, "WEBRequest", base64Encoder);
            logger.info("调用接口出参:{}",invoke);
            result = Base64Utils.getBase64Decoder(invoke);
            logger.info("调用接口出参解密:{}",result);
            Document documentResult = DocumentHelper.parseText(result);
            Element rootResult = documentResult.getRootElement();
            Element element = rootResult.element("接口");
            Element elementCzzt = element.element("操作状态");
            if (elementCzzt != null) {
                String code = elementCzzt.getText(); // 或 element.getTextTrim()
                if ("1".equals(code)){
                    Map param = new HashMap<>();
                    param.put("ID_REPORT",req.get("病例ID"));
                    param.put("SBZT",-1);
                    param.put("GUID",req.get("病例"));
                    updateEscalationStatus(param);
                    return  getSuccess(JSONArray.fromObject(result));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

//        HttpClientUtil.doPost();
        return result;
    }

    /**
     * 食源性报卡申请召回病例
     */
    @Override
    public String recallFoodborneIllness(Map<String, Object> req) {
        //上传数据业务逻辑处理
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("接口");
        root.addElement("令牌").addText(stringOf(req.get("令牌")));
        root.addElement("数据类型").addText("3");
        root.addElement("操作类型").addText("7");
        root.addElement("操作单位").addText(stringOf(req.get("操作单位")));
        root.addElement("操作用户").addText(stringOf(req.get("操作用户")));

        Element thxx = root.addElement("退回信息");
        thxx.addElement("病例").addText(stringOf(req.get("病例")));
        thxx.addElement("退回单位").addText(stringOf(req.get("退回单位")));
        Element thxxly = thxx.addElement("退回理由");
        thxxly.addElement("出生日期").addText(stringOf(req.get("出生日期")));
        thxxly.addElement("病人属于").addText(stringOf(req.get("病人属于")));
        thxxly.addElement("具体理由").addText(stringOf(req.get("具体理由")));

        //组装上传德数据
        String xml = document.asXML();
        logger.info("申请召回调用接口入参:{}",xml);
        String result;
        //调用上传地址
        try {
            String base64Encoder = Base64Utils.getBase64Encoder(xml);
            String invoke = ClientUtil.invoke(url, "WEBRequest", base64Encoder);
            logger.info("调用接口出参:{}",invoke);
            result = Base64Utils.getBase64Decoder(invoke);
            logger.info("调用接口出参解密:{}",result);
            Document documentResult = DocumentHelper.parseText(result);
            Element rootResult = documentResult.getRootElement();
            Element element = rootResult.element("接口");
            Element elementCzzt = element.element("操作状态");
            if (elementCzzt != null) {
                String code = elementCzzt.getText(); // 或 element.getTextTrim()
                if ("1".equals(code)){
                    Map param = new HashMap<>();
                    param.put("ID_REPORT",req.get("病例ID"));
                    param.put("SBZT",-2);
                    param.put("GUID",req.get("病例"));
                    updateEscalationStatus(param);
                    return  getSuccess(JSONArray.fromObject(result));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

//        HttpClientUtil.doPost();
        return result;
    }

    /**
     * 食源性报卡信息查询
     */
    @Override
    public String searchUrl(Map<String, Object> req) {
        //上传数据业务逻辑处理
        // Map → JSON
        Map<String,Object> bkList = new HashMap<>();
        bkList.put("doctorCode", stringOf(req.get("WORKNUMBER")));
        bkList.put("fillOrganization", stringOf(req.get("ID_ORG_CD")));
        bkList.put("businessType", stringOf(req.get("BUSINESSTYPE")));
        bkList.put("workNumber", stringOf(req.get("WORKNUMBER")));
        bkList.put("reportNumber", stringOf(req.get("ID_REPORT")));

        logger.info("食源性报卡信息查询json入参:{}",JSONUtil.toJsonStr(bkList));
        String ls_result=null;
        //调用上传地址
            String invoke = HttpClientUtil.doPostJsonsyx(url_bk, '['+JSONUtil.toJsonStr(bkList)+']',stringOf(req.get("TOKEN")));
            logger.info("调用接口出参:{}",invoke);
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(invoke);

            ls_result= root.path("body").path("url").asText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ls_result;
    }

    /**
     * 食源性报卡撤回病例
     */
    @Override
    public String revokeFoodborneIllness(Map<String, Object> req) {
        //上传数据业务逻辑处理
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("接口");
        root.addElement("令牌").addText(stringOf(req.get("令牌")));
        root.addElement("数据类型").addText("3");
        root.addElement("操作类型").addText("10");
        root.addElement("操作单位").addText(stringOf(req.get("操作单位")));
        root.addElement("操作用户").addText(stringOf(req.get("操作用户")));
        root.addElement("病例").addText(stringOf(req.get("病例")));


        //组装上传德数据
        String xml = document.asXML();
        logger.info("撤回病例调用接口入参:{}",xml);
        String result;
        //调用上传地址
        try {
            String base64Encoder = Base64Utils.getBase64Encoder(xml);
            String invoke = ClientUtil.invoke(url, "WEBRequest", base64Encoder);
            logger.info("调用接口出参:{}",invoke);
            result = Base64Utils.getBase64Decoder(invoke);
            logger.info("调用接口出参解密:{}",result);
            Document documentResult = DocumentHelper.parseText(result);
            Element rootResult = documentResult.getRootElement();
            Element element = rootResult.element("接口");
            Element elementCzzt = element.element("操作状态");
            if (elementCzzt != null) {
                String code = elementCzzt.getText(); // 或 element.getTextTrim()
                if ("1".equals(code)){
                    Map param = new HashMap<>();
                    param.put("ID_REPORT",req.get("病例ID"));
                    param.put("SBZT",-3);
                    param.put("GUID",req.get("病例"));
                    updateEscalationStatus(param);
                    return  getSuccess(JSONArray.fromObject(result));
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

//        HttpClientUtil.doPost();
        return result;
    }

    public static String stringOf(Object o) {
        return o == null ? "" : o.toString();
    }


}
